package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.parser.Feature;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil;
import cn.com.kh.AESUtil;

import org.json.JSONArray
import org.json.JSONException;

/**
 *
 * @Title: ApiBPCheck
 * @Description:深圳宝安排水小程序登录接口--内部接口
 * 验证客户是否属于客服系统的客户
 * @author: chieh
 * @date 2020-11-11 21:28:00
 *
 */
public class ApiBPCheck implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPCheck.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		
		log.debug("-------------------------start ApiBPCheck 开始-----------------");	
			
        long startTime = System.currentTimeMillis();
        String reJson = null;
        long endTime = 0;

		response.setContentType("application/json;charset=utf-8");
		
		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);
		String inData = "";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}
		
		// 调用处理信息
		//JSONObject inObject = JSONObject.parseObject(inData, Feature.OrderedField);
		JSONObject inObject = new JSONObject(inData);
		log.debug("处理前的Json：" + inObject.toString());
		
		//openid 排序问题
		JSONArray jsonArraytemp = new JSONArray(inObject.get("data").toString());
		log.debug("jsonArraytemp: " + jsonArraytemp);
		
		JSONObject dataObjecttemp = jsonArraytemp.getJSONObject(0);
		log.debug(dataObjecttemp);
		String openidtemp = GetJV(dataObjecttemp, "openid");
		log.debug("openid:"+openidtemp);
		
		String replaceString ="[{\"openid\":\""+openidtemp+"\"}]";
		log.debug("replaceString:"+replaceString);
		
		//鉴权加密处理--验证密码
		JSONObject checkJson = signUtil.CheckSign(inObject,replaceString);
		log.debug("checkJson: " + checkJson);

		if (checkJson != null) {
			log.debug("[签名校验异常-返回信息]:" + checkJson);
			endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败([签名校验异常-返回信息]:"+signUtil.jsonObjectToMap(checkJson)+"),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            return reJson;
		} else {
			log.debug("[签名校验成功]");
			// 校验成功
			//todo 业务逻辑
		}
		
		//data 获取参数openid
		JSONArray jsonArray = new JSONArray(inObject.get("data").toString());
		log.debug("jsonArray: " + jsonArray);
		String openid= jsonArray.getJSONObject(0).get("openid");
		log.debug("openid: " + openid);
        
		JSONArray resArray = new JSONArray();
        JSONObject resObject = new JSONObject();
        try {
            if (openid == null) {
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"验证失败(参数输入异常),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            }
			def custresult =eliteBean.chaxun_sql("select top 1 wechatid as wechatid,customername as customername,mobile as mobile from customer where wechatid='"+openid+"' order by createddate","dataSource");
			String wechatid = null;
			String customername = null;
			String mobile = null;
			int count=custresult.size();
			if(count > 0) {
				log.debug("count："+count);
				wechatid = custresult.get(0).get("wechatid");
				customername = custresult.get(0).get("customername");
				mobile = custresult.get(0).get("mobile");
				
				resObject.put("openid", wechatid);
				resObject.put("customername",customername);
				resObject.put("mobile",mobile);

				resArray.put(resObject);
				
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"验证成功，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+resArray+"}";
			}else{
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"2\",\"resultmessage\":\"验证未找到，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
			}
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"验证异常，接口调用处理失败(" + e.getMessage() + ")\",\"data\":[]}";

        }
        return reJson;

    }
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
}